package com.ywh.train.logic;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import com.ywh.train.Constants;
import com.ywh.train.Util;
import com.ywh.train.bean.Passenger;
import com.ywh.train.bean.Result;
import com.ywh.train.bean.TrainQueryInfo;
import com.ywh.train.bean.UserInfo;

public class TrainClient {
    Logger log = Logger.getLogger(getClass());
    private HttpClient httpclient = null;

    public TrainClient(HttpClient client) {
        this.httpclient = client;
    }
    
    public HttpClient getHttpclient() {
    	return this.httpclient;
    }
    
    public void setHttpclient(HttpClient httpclient) {
    	this.httpclient = httpclient;
    }

    public Map<String, String> submutOrderRequest(String rangDate, String startDate, TrainQueryInfo train) {
        this.log.debug("-------------------submutOrderRequest start-------------------");
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("station_train_code", train.getTrain_code()));
        formparams.add(new BasicNameValuePair("train_date", startDate));
        formparams.add(new BasicNameValuePair("seattype_num", ""));
        formparams.add(new BasicNameValuePair("from_station_telecode", train.getFromStationCode()));
        formparams.add(new BasicNameValuePair("to_station_telecode", train.getToStationCode()));
        formparams.add(new BasicNameValuePair("include_student", "00"));
        formparams.add(new BasicNameValuePair("from_station_telecode_name", train.getFromStation()));
        formparams.add(new BasicNameValuePair("to_station_telecode_name", train.getToStation()));
        formparams.add(new BasicNameValuePair("round_train_date", Util.getCurDate()));
        formparams.add(new BasicNameValuePair("round_start_time_str", rangDate));
        formparams.add(new BasicNameValuePair("single_round_type", "1"));
        formparams.add(new BasicNameValuePair("train_pass_type", "QB"));
        formparams.add(new BasicNameValuePair("train_class_arr", "QB#D#Z#T#K#QT#"));
        formparams.add(new BasicNameValuePair("start_time_str", rangDate));
        //formparams.add(new BasicNameValuePair("lishi", "" + Util.getHour2Min(train.getTakeTime())));
        formparams.add(new BasicNameValuePair("lishi", train.getLishi()));
        formparams.add(new BasicNameValuePair("train_start_time", train.getStartTime()));
        formparams.add(new BasicNameValuePair("trainno4", train.getTrain_no()));
        formparams.add(new BasicNameValuePair("arrive_time", train.getEndTime()));
        formparams.add(new BasicNameValuePair("from_station_name", train.getFromStation()));
        formparams.add(new BasicNameValuePair("to_station_name", train.getToStation()));
        formparams.add(new BasicNameValuePair("from_station_no", train.getFromStationNo()));
        formparams.add(new BasicNameValuePair("to_station_no", train.getToStationNo()));
        formparams.add(new BasicNameValuePair("ypInfoDetail", train.getYpInfoDetail()));
        formparams.add(new BasicNameValuePair("mmStr", train.getMmStr()));
        formparams.add(new BasicNameValuePair("locationCode", train.getLocationCode()));
        Map<String, String> map = new HashMap<String, String>();
        BufferedReader br = null;
        try {
            System.out.println("submutOrderRequest formparams :" + URLEncodedUtils.format(formparams, "UTF-8"));
            UrlEncodedFormEntity uef = new UrlEncodedFormEntity(formparams, "UTF-8");
            System.out.println("URL :" + Constants.Query_Single_Submut_OrderRequest_URL);
            HttpPost post = new HttpPost(Constants.Query_Single_Submut_OrderRequest_URL);
            post.addHeader("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
            post.addHeader("Referer", Constants.Query_Single_Init_URL);
            post.addHeader("Accept-Language", "zh-cn");
            post.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
            post.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //post.addHeader("Accept-Encoding", "gzip, deflate");
            post.addHeader("Host", Constants.Host_Location);
            //post.addHeader("Connection", "Keep-Alive");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader("Cookie", Constants.getCookie());
            post.setEntity(uef);
            HttpResponse response = this.httpclient.execute(post);
            HttpEntity entity = response.getEntity();
            br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
            	//System.out.println(line);
            }
            this.log.debug(response.getStatusLine());
            //Header[] locationHeader = response.getHeaders("Location");
            this.log.debug("-------------------get confirmPassenger & token start-------------------");
            System.out.println("URL :" + Constants.ConfirmPassenger_Init_URL);
            HttpGet get = new HttpGet(Constants.ConfirmPassenger_Init_URL);
            get.addHeader("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
            get.addHeader("Referer", Constants.Query_Single_Init_URL);
            get.addHeader("Accept-Language", "zh-cn");
            get.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
            //get.addHeader("Accept-Encoding", "gzip, deflate");
            get.addHeader("Host", Constants.Host_Location);
            //get.addHeader("Connection", "Keep-Alive");
            get.addHeader("Cache-Control", "no-cache");
            get.addHeader("Cookie", Constants.getCookie());
            String left_ticket = null;
            String token = null;
            BufferedReader br_2 = null;
            try {
                HttpResponse response_2 = this.httpclient.execute(get);
                HttpEntity entity_2 = response_2.getEntity();
                br_2 = new BufferedReader(new InputStreamReader(entity_2.getContent(), "UTF-8"));
                String line_2 = null;
                boolean left_ticket_flag = false;
            	System.out.println();
            	System.out.println("ConfirmPassenger_Init_URL :" + Constants.ConfirmPassenger_Init_URL);
                while ((line_2 = br_2.readLine()) != null) {
                	line_2 = line_2.replaceAll("&nbsp;", " ").replaceAll("\\s+", " ");
                	System.out.print(line_2);
                	if (line_2.indexOf("org.apache.struts.taglib.html.TOKEN") > -1) {
                        token = line_2;
                    }
					if (left_ticket_flag) {
						left_ticket = line_2;
						left_ticket_flag = false;
					} else {
						if (line_2.indexOf("left_ticket") > -1) {
							if (line_2.indexOf("value=") > -1) {
								left_ticket = line_2;
							} else {
								left_ticket_flag = true;
							}
						}
					}
                }
            	System.out.println();
				if (left_ticket != null) {
					int start = left_ticket.indexOf("value=\"");
					int end = left_ticket.indexOf("\"", start + 7);
                    left_ticket = left_ticket.substring(start + 7, end);
                } else {
                    this.log.warn("book ticket error, can't get left_ticket!");
                }
                if (token != null) {
					int start = token.indexOf("value=\"");
					int end = token.indexOf("\"", start + 7);
                    token = token.substring(start + 7, end);
                } else {
                    this.log.warn("book ticket error, can't get token!");
                }
            } catch (Exception e) {
                this.log.error(e);
            } finally {
                try {
                    if (br_2 != null)
                    	br_2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            this.log.debug("left_ticket = " + left_ticket);
			this.log.debug("token = " + token);
			map.put("leftTicketStr", left_ticket);
			map.put("token", token);
            this.log.debug("-------------------get confirmPassenger & token end-------------------");
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------submutOrderRequest end-------------------");
        return map;
    }

    public Map<String, String> getQueueCount(UserInfo user, TrainQueryInfo train, String left_ticket) {
        this.log.debug("-------------------getQueueCount start-------------------");
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("train_date", user.getTrain_date()));
        parameters.add(new BasicNameValuePair("train_no", train.getTrain_no()));
        parameters.add(new BasicNameValuePair("station", train.getTrain_code()));
        parameters.add(new BasicNameValuePair("seat", user.getSeat()));	
        parameters.add(new BasicNameValuePair("from", train.getFromStationCode()));
        parameters.add(new BasicNameValuePair("to", train.getToStationCode()));
        parameters.add(new BasicNameValuePair("ticket", left_ticket));
        System.out.println("URL :" + Constants.ConfirmPassenger_GetQueueCount_URL);
        System.out.println("getQueueCount formparams :" + Constants.ConfirmPassenger_GetQueueCount_URL + URLEncodedUtils.format(parameters, "UTF-8"));
        HttpGet get = new HttpGet(Constants.ConfirmPassenger_GetQueueCount_URL + URLEncodedUtils.format(parameters, "UTF-8"));
        get.addHeader("x-requested-with", "XMLHttpRequest");
        get.addHeader("Accept-Language", "zh-cn");
        get.addHeader("Referer", Constants.ConfirmPassenger_Init_URL);
        get.addHeader("Accept", "application/json, text/javascript, */*");
        get.addHeader("Content-Type", "application/x-www-form-urlencoded");
        //get.addHeader("Accept-Encoding", "gzip, deflate");
        get.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
        get.addHeader("Host", Constants.Host_Location);
        //get.addHeader("Connection", "Keep-Alive");
        get.addHeader("Cookie", Constants.getCookie());
        String json = null;
		Map<String, String> map = new HashMap<String, String>();
		try {
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			json = (String) this.httpclient.execute(get, responseHandler);
        	System.out.println();
        	System.out.println("ConfirmPassenger_GetQueueCount_URL :" + Constants.ConfirmPassenger_GetQueueCount_URL);
        	System.out.println(json);
			this.log.debug(json);
			map = Util.jsonToMap(json);
		} catch (Exception e) {
			this.log.error(e);
		}
        this.log.debug("-------------------getQueueCount end-------------------");
        return map;
    }

    public Map<String, String> querySingleInit() {
        this.log.debug("-------------------querySingleInit start-------------------");
        System.out.println("URL :" + Constants.Query_Single_Init_URL);
        HttpGet get = new HttpGet(Constants.Query_Single_Init_URL);
        get.addHeader("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        get.addHeader("Referer", Constants.Login_URL);
        get.addHeader("Accept-Language", "zh-cn");
        get.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
        //get.addHeader("Accept-Encoding", "gzip, deflate");
        get.addHeader("Host", Constants.Host_Location);
        //get.addHeader("Connection", "Keep-Alive");
        get.addHeader("Cookie", Constants.getCookie());
        //String json = null;
		Map<String, String> map = new HashMap<String, String>();
		try {
            String token = null;
            BufferedReader br = null;
            try {
                HttpResponse response = this.httpclient.execute(get);
                HttpEntity entity = response.getEntity();
                br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                String line = null;
            	System.out.println();
            	System.out.println("Query_Single_Init_URL :" + Constants.Query_Single_Init_URL);
                while ((line = br.readLine()) != null) {
                	line = line.replaceAll("&nbsp;", " ").replaceAll("\\s+", " ");
                	System.out.println(line);
                    if (line.indexOf("org.apache.struts.taglib.html.TOKEN") > -1) {
                        token = line;
                    }
                }
            	System.out.println();
                if (token != null) {
                    int start = token.indexOf("value=\"");
                    int end = token.indexOf("\"", start + 7);
                    token = token.substring(start + 7, end);
                } else {
                    this.log.warn("book ticket error, can't get token!");
                }
            } catch (Exception e) {
                this.log.error(e);
            } finally {
                try {
                    if (br != null)
                        br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
			this.log.debug("token = " + token);
			map.put("token", token);
		} catch (Exception e) {
			this.log.error(e);
		}
        this.log.debug("-------------------querySingleInit end-------------------");
        return map;
    }

    public List<Passenger> getPassengerJson() {
        this.log.debug("-------------------order PassengerJson start-------------------");
        System.out.println("URL :" + Constants.ConfirmPassenger_GetpassengerJson_URL);
        HttpPost post = new HttpPost(Constants.ConfirmPassenger_GetpassengerJson_URL);
        post.addHeader("x-requested-with", "XMLHttpRequest");
        post.addHeader("Accept-Language", "zh-cn");
        post.addHeader("Referer", Constants.ConfirmPassenger_Init_URL);
        post.addHeader("Accept", "application/json, text/javascript, */*");
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        //post.addHeader("Accept-Encoding", "gzip, deflate");
        post.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
        post.addHeader("Host", Constants.Host_Location);
        //post.addHeader("Connection", "Keep-Alive");
        post.addHeader("Cache-Control", "no-cache");
        post.addHeader("Cookie", Constants.getCookie());
        String passengerJson = null;
        List<Passenger> passengers = null;
		try {
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			passengerJson = (String) this.httpclient.execute(post, responseHandler);
        	System.out.println();
        	System.out.println("ConfirmPassenger_GetpassengerJson_URL :" + Constants.ConfirmPassenger_GetpassengerJson_URL);
            System.out.println(passengerJson);
			this.log.debug(passengerJson);
			passengers = Util.parsePassengerJson(passengerJson);
		} catch (Exception e) {
			this.log.error(e);
		}
        this.log.debug("-------------------order PassengerJson end-------------------");
        return passengers;
    }

    public Map<String, String> queryOrderWaitTime(String tourFlag) {
        this.log.debug("-------------------order WaitTime start-------------------");
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("tourFlag", tourFlag));
        System.out.println("URL :" + Constants.MyOrder_QueryOrderWaitTime_URL);
        System.out.println("orderWaitTime formparams :" + Constants.MyOrder_QueryOrderWaitTime_URL + URLEncodedUtils.format(parameters, "UTF-8"));
        HttpGet get = new HttpGet(Constants.MyOrder_QueryOrderWaitTime_URL + URLEncodedUtils.format(parameters, "UTF-8"));
        get.addHeader("x-requested-with", "XMLHttpRequest");
        get.addHeader("Accept-Language", "zh-cn");
        get.addHeader("Referer", Constants.ConfirmPassenger_Init_URL);
        get.addHeader("Accept", "application/json, text/javascript, */*");
        get.addHeader("Content-Type", "application/x-www-form-urlencoded");
        //get.addHeader("Accept-Encoding", "gzip, deflate");
        get.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
        get.addHeader("Host", Constants.Host_Location);
        //get.addHeader("Connection", "Keep-Alive");
        get.addHeader("Cookie", Constants.getCookie());
        String json = null;
		Map<String, String> map = new HashMap<String, String>();
        try {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            json = (String) this.httpclient.execute(get, responseHandler);
        	System.out.println();
        	System.out.println("MyOrder_QueryOrderWaitTime_URL :" + Constants.MyOrder_QueryOrderWaitTime_URL);
            System.out.println(json);
            this.log.debug(json);
            map = Util.jsonToMap(json);
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------order WaitTime end-------------------");
        return map;
    }
    
    private List<NameValuePair> getFormparams(String randCode, String token, UserInfo user, TrainQueryInfo train, List<Passenger> passengers, String leftTicketStr, String tourFlag) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("org.apache.struts.taglib.html.TOKEN", token));
        formparams.add(new BasicNameValuePair("leftTicketStr", leftTicketStr));
        formparams.add(new BasicNameValuePair("textfield", "中文或拼音首字母"));
        Map<String, Passenger> passengerMap = Util.genPassengerMap(passengers);
        if (!"".equals(user.getCardno1())) {
            Passenger passenger = passengerMap.get(user.getCardno1());
            if (passenger != null) {
                formparams.add(new BasicNameValuePair("checkbox" + passenger.getOrderno(), passenger.getOrderno()));
            }
        }
        if (!"".equals(user.getCardno2())) {
            Passenger passenger = passengerMap.get(user.getCardno2());
            if (passenger != null) {
                formparams.add(new BasicNameValuePair("checkbox" + passenger.getOrderno(), passenger.getOrderno()));
            }
        }
        if (!"".equals(user.getCardno3())) {
            Passenger passenger = passengerMap.get(user.getCardno3());
            if (passenger != null) {
                formparams.add(new BasicNameValuePair("checkbox" + passenger.getOrderno(), passenger.getOrderno()));
            }
        }
        if (!"".equals(user.getCardno4())) {
            Passenger passenger = passengerMap.get(user.getCardno4());
            if (passenger != null) {
                formparams.add(new BasicNameValuePair("checkbox" + passenger.getOrderno(), passenger.getOrderno()));
            }
        }
        if (!"".equals(user.getCardno5())) {
            Passenger passenger = passengerMap.get(user.getCardno5());
            if (passenger != null) {
                formparams.add(new BasicNameValuePair("checkbox" + passenger.getOrderno(), passenger.getOrderno()));
            }
        }
        formparams.add(new BasicNameValuePair("orderRequest.train_date", user.getTrain_date())); // "2011-11-28"
        formparams.add(new BasicNameValuePair("orderRequest.train_no", train.getTrain_no()));
        formparams.add(new BasicNameValuePair("orderRequest.station_train_code", train.getTrain_code()));
        formparams.add(new BasicNameValuePair("orderRequest.from_station_telecode", train.getFromStationCode()));
        formparams.add(new BasicNameValuePair("orderRequest.to_station_telecode", train.getToStationCode()));
        formparams.add(new BasicNameValuePair("orderRequest.seat_type_code", ""));
        formparams.add(new BasicNameValuePair("orderRequest.ticket_type_order_num", ""));
        formparams.add(new BasicNameValuePair("orderRequest.bed_level_order_num", "000000000000000000000000000000"));
        formparams.add(new BasicNameValuePair("orderRequest.start_time", train.getStartTime()));
        formparams.add(new BasicNameValuePair("orderRequest.end_time", train.getEndTime()));
        formparams.add(new BasicNameValuePair("orderRequest.from_station_name", train.getFromStation()));
        formparams.add(new BasicNameValuePair("orderRequest.to_station_name", train.getToStation()));
        formparams.add(new BasicNameValuePair("orderRequest.cancel_flag", "1"));
        formparams.add(new BasicNameValuePair("orderRequest.id_mode", user.getId_mode())); // "Y"
        if (!"".equals(user.getCardno1())) {
        	formparams.add(new BasicNameValuePair("passengerTickets", user.getText1()));
            formparams.add(new BasicNameValuePair("oldPassengers", user.getOldSimpleText1()));
            formparams.add(new BasicNameValuePair("passenger_1_seat", user.getSeat()));
            formparams.add(new BasicNameValuePair("passenger_1_ticket", user.getTicket()));
            formparams.add(new BasicNameValuePair("passenger_1_name", user.getName1()));
            formparams.add(new BasicNameValuePair("passenger_1_cardtype", user.getCardtype()));
            formparams.add(new BasicNameValuePair("passenger_1_cardno", user.getCardno1()));
            formparams.add(new BasicNameValuePair("passenger_1_mobileno", user.getMobileno1()));
        } else {
            formparams.add(new BasicNameValuePair("oldPassengers", ""));
        }
        formparams.add(new BasicNameValuePair("checkbox9", "Y"));
        if (!"".equals(user.getCardno2())) {
        	formparams.add(new BasicNameValuePair("passengerTickets", user.getText2()));
            formparams.add(new BasicNameValuePair("oldPassengers", user.getOldSimpleText2()));
            formparams.add(new BasicNameValuePair("passenger_2_seat", user.getSeat()));
            formparams.add(new BasicNameValuePair("passenger_2_ticket", user.getTicket()));
            formparams.add(new BasicNameValuePair("passenger_2_name", user.getName2()));
            formparams.add(new BasicNameValuePair("passenger_2_cardtype", user.getCardtype()));
            formparams.add(new BasicNameValuePair("passenger_2_cardno", user.getCardno2()));
            formparams.add(new BasicNameValuePair("passenger_2_mobileno", user.getMobileno2()));
        } else {
            formparams.add(new BasicNameValuePair("oldPassengers", ""));
        }
        formparams.add(new BasicNameValuePair("checkbox9", "Y"));
        if (!"".equals(user.getCardno3())) {
        	formparams.add(new BasicNameValuePair("passengerTickets", user.getText3()));
            formparams.add(new BasicNameValuePair("oldPassengers", user.getOldSimpleText3()));
            formparams.add(new BasicNameValuePair("passenger_3_seat", user.getSeat()));
            formparams.add(new BasicNameValuePair("passenger_3_ticket", user.getTicket()));
            formparams.add(new BasicNameValuePair("passenger_3_name", user.getName3()));
            formparams.add(new BasicNameValuePair("passenger_3_cardtype", user.getCardtype()));
            formparams.add(new BasicNameValuePair("passenger_3_cardno", user.getCardno3()));
            formparams.add(new BasicNameValuePair("passenger_3_mobileno", user.getMobileno3()));
        } else {
            formparams.add(new BasicNameValuePair("oldPassengers", ""));
        }
        formparams.add(new BasicNameValuePair("checkbox9", "Y"));
        if (!"".equals(user.getCardno4())) {
        	formparams.add(new BasicNameValuePair("passengerTickets", user.getText4()));
            formparams.add(new BasicNameValuePair("oldPassengers", user.getOldSimpleText4()));
            formparams.add(new BasicNameValuePair("passenger_4_seat", user.getSeat()));
            formparams.add(new BasicNameValuePair("passenger_4_ticket", user.getTicket()));
            formparams.add(new BasicNameValuePair("passenger_4_name", user.getName4()));
            formparams.add(new BasicNameValuePair("passenger_4_cardtype", user.getCardtype()));
            formparams.add(new BasicNameValuePair("passenger_4_cardno", user.getCardno4()));
            formparams.add(new BasicNameValuePair("passenger_4_mobileno", user.getMobileno4()));
        } else {
            formparams.add(new BasicNameValuePair("oldPassengers", ""));
        }
        formparams.add(new BasicNameValuePair("checkbox9", "Y"));
        if (!"".equals(user.getCardno5())) {
        	formparams.add(new BasicNameValuePair("passengerTickets", user.getText5()));
            formparams.add(new BasicNameValuePair("oldPassengers", user.getOldSimpleText5()));
            formparams.add(new BasicNameValuePair("passenger_5_seat", user.getSeat()));
            formparams.add(new BasicNameValuePair("passenger_5_ticket", user.getTicket()));
            formparams.add(new BasicNameValuePair("passenger_5_name", user.getName5()));
            formparams.add(new BasicNameValuePair("passenger_5_cardtype", user.getCardtype()));
            formparams.add(new BasicNameValuePair("passenger_5_cardno", user.getCardno5()));
            formparams.add(new BasicNameValuePair("passenger_5_mobileno", user.getMobileno5()));
        } else {
            formparams.add(new BasicNameValuePair("oldPassengers", ""));
        }
        formparams.add(new BasicNameValuePair("checkbox9", "Y"));
        formparams.add(new BasicNameValuePair("randCode", randCode));
        formparams.add(new BasicNameValuePair("orderRequest.reserve_flag", "A"));
		if (tourFlag != null && !"".equals(tourFlag)) {
			formparams.add(new BasicNameValuePair("tFlag", tourFlag));
		}
        return formparams;
    }

    public Map<String, String> checkOrderInfo(String randCode, String token, UserInfo user, TrainQueryInfo train, List<Passenger> passengers, String leftTicketStr, String tourFlag) {
        this.log.debug("-------------------checkOrderInfo start-------------------");
        System.out.println("URL :" + Constants.ConfirmPassenger_checkOrderInfo_URL);
		HttpPost post = new HttpPost(Constants.ConfirmPassenger_checkOrderInfo_URL + randCode);
        List<NameValuePair> formparams = this.getFormparams(randCode, token, user, train, passengers, leftTicketStr, tourFlag);
        String json = null;
        Map<String, String> map = new HashMap<String, String>();
        try {
            System.out.println("checkOrderInfo formparams :" + URLEncodedUtils.format(formparams, "UTF-8"));
            UrlEncodedFormEntity uef = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.setEntity(uef);
            post.addHeader("x-requested-with", "XMLHttpRequest");
            post.addHeader("Accept-Language", "zh-cn");
            post.addHeader("Referer", Constants.ConfirmPassenger_Init_URL);
            post.addHeader("Accept", "application/json, text/javascript, */*");
            post.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //post.addHeader("Accept-Encoding", "gzip, deflate");
            post.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
            post.addHeader("Host", Constants.Host_Location);
            //post.addHeader("Connection", "Keep-Alive");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader("Cookie", Constants.getCookie());
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            json = (String) this.httpclient.execute(post, responseHandler);
        	System.out.println();
        	System.out.println("ConfirmPassenger_checkOrderInfo_URL :" + Constants.ConfirmPassenger_checkOrderInfo_URL);
            System.out.println(json);
            this.log.debug(json);
            map = Util.jsonToMap(json);
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------checkOrderInfo end-------------------");
        return map;
    }

    public Map<String, String> confirmSingleForQueueOrder(String randCode, String token, UserInfo user, TrainQueryInfo train, List<Passenger> passengers, String leftTicketStr) {
        this.log.debug("-------------------confirmSingleForQueueOrder start-------------------");
        System.out.println("URL :" + Constants.SUBMIT_dc_QueueOrder_URL);
        HttpPost post = new HttpPost(Constants.SUBMIT_dc_QueueOrder_URL);
        List<NameValuePair> formparams = this.getFormparams(randCode, token, user, train, passengers, leftTicketStr, null);
        System.out.println("confirmSingleForQueueOrder formparams :" + URLEncodedUtils.format(formparams, "UTF-8"));
        String json = null;
        Map<String, String> map = new HashMap<String, String>();
        try {
            UrlEncodedFormEntity uef = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.setEntity(uef);
            post.addHeader("x-requested-with", "XMLHttpRequest");
            post.addHeader("Accept-Language", "zh-cn");
            post.addHeader("Referer", Constants.ConfirmPassenger_Init_URL);
            post.addHeader("Accept", "application/json, text/javascript, */*");
            post.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //post.addHeader("Accept-Encoding", "gzip, deflate");
            post.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
            post.addHeader("Host", Constants.Host_Location);
            //post.addHeader("Connection", "Keep-Alive");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader("Cookie", Constants.getCookie());
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            json = (String) this.httpclient.execute(post, responseHandler);
        	System.out.println();
        	System.out.println("SUBMIT_dc_QueueOrder_URL :" + Constants.SUBMIT_dc_QueueOrder_URL);
            System.out.println(json);
            this.log.debug(json);
            map = Util.jsonToMap(json);
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------confirmSingleForQueueOrder end-------------------");
        return map;
    }

    public Map<String, String> confirmSingleForQueue(String randCode, String token, UserInfo user, TrainQueryInfo train, List<Passenger> passengers, String leftTicketStr) {
        this.log.debug("-------------------confirmSingleForQueue start-------------------");
        System.out.println("URL :" + Constants.SUBMIT_dc_Queue_URL);
        HttpPost post = new HttpPost(Constants.SUBMIT_dc_Queue_URL);
        List<NameValuePair> formparams = this.getFormparams(randCode, token, user, train, passengers, leftTicketStr, null);
        System.out.println("confirmSingleForQueue formparams :" + URLEncodedUtils.format(formparams, "UTF-8"));
        String json = "";
        //String Location = "";
        BufferedReader br = null;
        Map<String, String> map = new HashMap<String, String>();
        try {
            UrlEncodedFormEntity uef = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.setEntity(uef);
            post.addHeader("x-requested-with", "XMLHttpRequest");
            post.addHeader("Accept-Language", "zh-cn");
            post.addHeader("Referer", Constants.ConfirmPassenger_Init_URL);
            post.addHeader("Accept", "application/json, text/javascript, */*");
            post.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //post.addHeader("Accept-Encoding", "gzip, deflate");
            post.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
            post.addHeader("Host", Constants.Host_Location);
            //post.addHeader("Connection", "Keep-Alive");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader("Cookie", Constants.getCookie());
            //ResponseHandler<String> responseHandler = new BasicResponseHandler();
            //json = (String) this.httpclient.execute(post, responseHandler);
        	//System.out.println();
        	//System.out.println("SUBMIT_dc_Queue_URL :" + Constants.SUBMIT_dc_Queue_URL);
            //System.out.println(json);
            //this.log.debug(json);
            //map = Util.jsonToMap(json);
            HttpResponse response = this.httpclient.execute(post);
            //Header header = response.getLastHeader("Location");
            HttpEntity entity = response.getEntity();
            br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
            String line = null;
        	System.out.println();
        	System.out.println("confirmSingleForQueue URL :" + Constants.SUBMIT_dc_Queue_URL);
            while ((line = br.readLine()) != null) {
            	json = json + line;
            }
            //if(header != null ) {
            //	Location = header.getValue();
			//}
			System.out.println(json);
			this.log.debug(json);
			map = Util.jsonToMap(json);
			//map.put("Location", Location);
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------confirmSingleForQueue end-------------------");
        return map;
    }

    public Result finishFunSubmitOrder(String randCode, String token, UserInfo user, TrainQueryInfo train, List<Passenger> passengers, String leftTicketStr, String orderId) {
        this.log.debug("-------------------finishFunSubmit order start-------------------");
        Result rs = new Result();
        System.out.println("URL :" + Constants.SUBMIT_finishFun_dc_QueueOrder_URL);
        HttpPost post = new HttpPost(Constants.SUBMIT_finishFun_dc_QueueOrder_URL + orderId);
        List<NameValuePair> formparams = this.getFormparams(randCode, token, user, train, passengers, leftTicketStr, null);
        String responseBody = null;
        try {
            System.out.println("finishFunSubmitOrder formparams :" + URLEncodedUtils.format(formparams, "UTF-8"));
            UrlEncodedFormEntity uef = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.setEntity(uef);
            post.addHeader("Accept-Language", "zh-cn");
            post.addHeader("Referer", Constants.ConfirmPassenger_Init_URL);
            post.addHeader("Accept", "application/json, text/javascript, */*");
            post.addHeader("Content-Type", "application/x-www-form-urlencoded");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader("Cookie", Constants.getCookie());
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            responseBody = (String) this.httpclient.execute(post, responseHandler);
        	System.out.println();
        	System.out.println("SUBMIT_finishFun_dc_QueueOrder_URL :" + Constants.SUBMIT_finishFun_dc_QueueOrder_URL);
            //System.out.println(responseBody);
            String ans = Util.removeTagFromHtml(responseBody);
            System.out.println(ans);
            if (ans.contains("订单信息")) {
                rs.setState(Result.SUCC);
                int beginIndex = ans.indexOf("订单信息");
                int endIndex = ans.indexOf("重新购票");
                rs.setMsg(ans.substring(beginIndex, endIndex));
            } else if (ans.isEmpty()) {
                rs.setState(Result.SUCC);
                rs.setMsg("好像订票成功了");
            } else if (ans.contains("由于您取消次数过多")) {
                rs.setState(Result.CANCEL_TIMES_TOO_MUCH);
                rs.setMsg(ans);
            } else if (ans.contains("验证码不正确") || ans.contains("请输入正确的验证码")) {
                rs.setState(Result.RAND_CODE_ERROR);
                rs.setMsg(ans);
            } else if (ans.contains("售票实行实名制")) {
                rs.setState(Result.REPEAT_BUY_TICKET);
                rs.setMsg(ans);
            } else if (ans.contains("号码输入有误")) {
                rs.setState(Result.ERROR_CARD_NUMBER);
                rs.setMsg(ans);
            } else if (ans.contains("当前提交订单用户过多")) {
                rs.setState(Result.CURRENT_USER_SOMANY);
                rs.setMsg(ans);
            } else {
                rs.setState(Result.OTHER);
                rs.setMsg(ans);
            }
            this.log.debug(ans);
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------finishFunSubmit order end-------------------");
        return rs;
    }

    public List<TrainQueryInfo> queryLeftTicket(String from, String to, String startDate, String rangDate, String trainNo, String seatType, String seatNum) {
        this.log.debug("-------------------query train start-------------------");
        if ((rangDate == null) || (rangDate.isEmpty())) {
            rangDate = "00:00--24:00";
        }
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        //parameters.add(new BasicNameValuePair("method", "queryLeftTicket"));
        parameters.add(new BasicNameValuePair("orderRequest.train_date", startDate));
        parameters.add(new BasicNameValuePair("orderRequest.from_station_telecode", Util.getCityCode(from)));
        parameters.add(new BasicNameValuePair("orderRequest.to_station_telecode", Util.getCityCode(to)));
        //parameters.add(new BasicNameValuePair("orderRequest.train_no", trainNo));
        parameters.add(new BasicNameValuePair("orderRequest.train_no", ""));
        parameters.add(new BasicNameValuePair("trainPassType", "QB"));
        parameters.add(new BasicNameValuePair("trainClass", "QB#D#Z#T#K#QT#"));
        parameters.add(new BasicNameValuePair("includeStudent", "00"));
        parameters.add(new BasicNameValuePair("seatTypeAndNum", ""));
        parameters.add(new BasicNameValuePair("orderRequest.start_time_str", rangDate));
        /*if (seatType != null && !"".equals(seatType) && !"none".equals(seatType)) {
            parameters.add(new BasicNameValuePair("orderRequest.seat_type_code", seatType));
            parameters.add(new BasicNameValuePair("seatNum", seatNum));
        }*/
        System.out.println("URL :" + Constants.Query_LeftTicket_URL);
        System.out.println("queryTrain formparams :" + Constants.Query_LeftTicket_URL + URLEncodedUtils.format(parameters, "UTF-8"));
        HttpGet get = new HttpGet(Constants.Query_LeftTicket_URL + URLEncodedUtils.format(parameters, "UTF-8"));
        get.addHeader("x-requested-with", "XMLHttpRequest");
        get.addHeader("Accept-Language", "zh-cn");
        get.addHeader("Referer", Constants.Query_Single_Init_URL);
        get.addHeader("Accept", "text/plain, */*");
        get.addHeader("Content-Type", "application/x-www-form-urlencoded");
        //get.addHeader("Accept-Encoding", "gzip, deflate");
        get.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
        get.addHeader("Host", Constants.Host_Location);
        //get.addHeader("Connection", "Keep-Alive");
        get.addHeader("Cookie", Constants.getCookie());
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = null;
        List<TrainQueryInfo> all = new ArrayList<TrainQueryInfo>();
        try {
            responseBody = (String) this.httpclient.execute(get, responseHandler);
            responseBody = responseBody.replaceAll("&nbsp;", "").replaceAll("\\s+", " ");
        	System.out.println();
        	System.out.println("Query_LeftTicket_URL :" + Constants.Query_LeftTicket_URL);
            System.out.println(responseBody);
            all = Util.parserQueryInfo(responseBody);
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------query train end-------------------");
        return all;
    }
    
    public Map<String, String> loginOtsweb() {
        this.log.debug("-------------------loginOtsweb start-------------------");
        Result rs = new Result();
        System.out.println("URL :" + Constants.Login_Otsweb_URL);
        HttpGet httpget = new HttpGet(Constants.Login_Otsweb_URL);
        //httpget.addHeader("Referer", Constants.Login_Kyfw_URL);
        httpget.addHeader("Accept-Language", "zh-cn");
        httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
        //httpget.addHeader("Accept-Encoding", "gzip, deflate");
        httpget.addHeader("Host", Constants.Host_Location);
        //httpget.addHeader("Connection", "Keep-Alive");
        httpget.addHeader("Cookie", Constants.getCookie());
        Map<String, String> map = new HashMap<String, String>();
        BufferedReader br = null;
        //String Location = null;
        String cookies = "";
        try {
            HttpResponse response = this.httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            //Header Locationheader = response.getLastHeader("Location");
            Header[] cookieheaders = response.getHeaders("Set-Cookie");
            //if (Locationheader != null) {
            //    Location = Locationheader.getValue();
            //}
			for(Header cookieheader : cookieheaders) {
				cookies = cookies + "$" + cookieheader.getValue();
			}
            br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
            }
        } catch (Exception e) {
            this.log.error(e);
        } finally {
            try {
                if (br != null)
                	br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //map.put("Location", Location);
		map.put("cookies", cookies);
        this.log.debug("-------------------loginOtsweb end---------------------");
        return map;
    }
    
    public Map<String, String> loginInit() {
        this.log.debug("-------------------login init start-------------------");
        Result rs = new Result();
        System.out.println("URL :" + Constants.Login_Init_URL);
        HttpGet httpget = new HttpGet(Constants.Login_Init_URL);
        httpget.addHeader("Referer", Constants.Login_Otsweb_URL);
        httpget.addHeader("Accept-Language", "zh-cn");
        httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
        //httpget.addHeader("Accept-Encoding", "gzip, deflate");
        httpget.addHeader("Host", Constants.Host_Location);
        //httpget.addHeader("Connection", "Keep-Alive");
        httpget.addHeader("Cookie", Constants.getCookie());
        Map<String, String> map = new HashMap<String, String>();
        BufferedReader br = null;
        String refundLoginCheck = null;
        String refundLoginChecked = null;
        //String Location = null;
        //String cookies = "";
        try {
            HttpResponse response = this.httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            //Header Locationheader = response.getLastHeader("Location");
            //Header[] cookieheaders = response.getHeaders("Set-Cookie");
			//if (Locationheader != null) {
			//	Location = Locationheader.getValue();
			//}
			//for(Header cookieheader : cookieheaders) {
			//	cookies = cookies + "$" + cookieheader.getValue();
			//}
            br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

            String line = null;
        	System.out.println();
        	System.out.println("Login_Init_URL :" + Constants.Login_Init_URL);
            while ((line = br.readLine()) != null) {
            	line = line.replaceAll("&nbsp;", " ").replaceAll("\\s+", " ");
                if (line.indexOf("refundLoginCheck") > -1) {
                	refundLoginCheck = line;
                }
            }
        	System.out.println();
            if (refundLoginCheck != null) {
                int start = refundLoginCheck.indexOf("value=\"");
				int end = refundLoginCheck.indexOf("\"", start + 7);
				if(refundLoginCheck.contains("checked")) {
					refundLoginChecked = "true";
				}
				refundLoginCheck = refundLoginCheck.substring(start + 7, end);
            } else {
                this.log.warn("login init error, can't get refundLoginCheck!");
            }
        } catch (Exception e) {
            this.log.error(e);
        } finally {
            try {
                if (br != null)
                	br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		this.log.debug("refundLoginCheck = " + refundLoginCheck);
		this.log.debug("refundLoginChecked = " + refundLoginChecked);
		map.put("refundLoginCheck", refundLoginCheck);
		map.put("refundLoginChecked", refundLoginChecked);
		//map.put("Location", Location);
		//map.put("cookies", cookies);
        this.log.debug("-------------------login init end---------------------");
        return map;
    }

    public Result login(String username, String password, String randCode, String loginRand, String refundLogin, String refundFlag, String randErrorFocus, boolean randerr) {
        this.log.debug("-----------------login start-----------------------");
        Result rs = new Result();
        System.out.println("URL :" + Constants.Login_URL);
        HttpPost httppost = new HttpPost(Constants.Login_URL);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("loginRand", loginRand));
        parameters.add(new BasicNameValuePair("refundLogin", refundLogin));
        parameters.add(new BasicNameValuePair("refundFlag", refundFlag));
        parameters.add(new BasicNameValuePair("loginUser.user_name", username));
        parameters.add(new BasicNameValuePair("nameErrorFocus", ""));
        parameters.add(new BasicNameValuePair("user.password", password));
        parameters.add(new BasicNameValuePair("passwordErrorFocus", ""));
        parameters.add(new BasicNameValuePair("randCode", randCode));
        parameters.add(new BasicNameValuePair("randErrorFocus", randErrorFocus));
        String responseBody = null;
        try {
            System.out.println("login formparams :" + URLEncodedUtils.format(parameters, "UTF-8"));
            UrlEncodedFormEntity uef = new UrlEncodedFormEntity(parameters, "UTF-8");
            if (randerr) {
                httppost.addHeader("Referer", Constants.Login_URL);
            } else {
                httppost.addHeader("Referer", Constants.Login_Init_URL);
            }
            httppost.addHeader("Accept-Language", "zh-cn");
    		httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    		httppost.addHeader("Accept", "application/json, text/javascript, */*");
    		httppost.addHeader("Cache-Control", "no-cache");
    		httppost.addHeader("Cookie", Constants.getCookie());
            httppost.setEntity(uef);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            responseBody = (String) this.httpclient.execute(httppost, responseHandler);
        	System.out.println();
        	System.out.println("Login_URL :" + Constants.Login_URL);
            //System.out.println(responseBody);
        	String message = Util.getMessageFromHtml(responseBody);
            String info = Util.removeTagFromHtml(responseBody);
            System.out.println(info);
            if(message != null && (message.contains("登录名不存在") || message.contains("用户名不存在") || message.contains("用户不存在") || message.contains("请输入正确的验证码") || message.contains("验证码不正确") ||  message.contains("验证码错误"))) {
                rs.setState(Result.FAIL);
                if(message.contains("登录名不存在") || message.contains("用户名不存在") || message.contains("用户不存在")) {
                	rs.setMsg("用户:" + username + " 登录失败,登录名不存在！");
                } else if(message.contains("请输入正确的验证码") || message.contains("验证码不正确") ||  message.contains("验证码错误")) {
	                rs.setMsg("用户:" + username + " 登录失败,请输入正确的验证码！");
                }
            } else {
	            if (info.contains("如果您需要预订车票，请您点")) {
	                //int index = info.indexOf("-->");
	                //this.log.debug(info.substring(index + 4));
	                rs.setState(Result.SUCC);
	                rs.setMsg("用户:" + username + " 登录成功");
	            } else if(info.contains("请输入正确的验证码") || info.contains("验证码不正确") ||  info.contains("验证码错误")) {
	                rs.setState(Result.FAIL);
	                rs.setMsg("用户:" + username + " 登录失败,请输入正确的验证码！");
	            } else {
	                rs.setState(Result.FAIL);
	                rs.setMsg("用户:" + username + " 登录失败," + info);
	            }
            }
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------login end---------------------");
        return rs;
    }

    public Map<String, String> loginAysnSuggest(boolean randerr) {
        this.log.debug("-----------------login AysnSuggest start-----------------------");
        System.out.println("URL :" + Constants.Login_AysnSuggest_URL);
		HttpPost httppost = new HttpPost(Constants.Login_AysnSuggest_URL);
		httppost.addHeader("x-requested-with", "XMLHttpRequest");
		httppost.addHeader("Accept-Language", "zh-cn");
		if(randerr) {
			httppost.addHeader("Referer", Constants.Login_URL);
		}else {
			httppost.addHeader("Referer", Constants.Login_Init_URL);
		}
		httppost.addHeader("Accept", "application/json, text/javascript, */*");
		httppost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
		httppost.addHeader("Host", Constants.Host_Location);
		httppost.addHeader("Cache-Control", "no-cache");
		httppost.addHeader("Cookie", Constants.getCookie());
        //List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		String json = null;
		Map<String, String> map = new HashMap<String, String>();
        try {
            //UrlEncodedFormEntity uef = new UrlEncodedFormEntity(parameters, "UTF-8");
            //httppost.setEntity(uef);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            json = (String) this.httpclient.execute(httppost, responseHandler);
        	System.out.println();
        	System.out.println("Login_AysnSuggest_URL :" + Constants.Login_AysnSuggest_URL);
            System.out.println(json);
            this.log.debug(json);
            map = Util.jsonToMap(json);
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------login AysnSuggest end---------------------");
        return map;
    }

    public Result queryOrder() {
        this.log.debug("-------------------query order start-------------------");
        Result rs = new Result();
        System.out.println("URL :" + Constants.QUERY_ORDER_URL);
        HttpGet httpget = new HttpGet(Constants.QUERY_ORDER_URL);
        httpget.addHeader("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        httpget.addHeader("Referer", Constants.Login_URL);
        httpget.addHeader("Accept-Language", "zh-cn");
        httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
        //httpget.addHeader("Accept-Encoding", "gzip, deflate");
        httpget.addHeader("Host", Constants.Host_Location);
        //httpget.addHeader("Connection", "Keep-Alive");
        httpget.addHeader("Cookie", Constants.getCookie());
        String responseBody = null;
        try {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            responseBody = this.httpclient.execute(httpget, responseHandler);
        	System.out.println();
        	System.out.println("Login_AysnSuggest_URL :" + Constants.Login_AysnSuggest_URL);
            //System.out.println(responseBody);
            String msg = Util.removeTagFromHtml(responseBody);
            System.out.println(msg);
			if (!msg.isEmpty()) {
				int beginIndex = msg.indexOf("订单时间");
				if (beginIndex != -1) {
					int endIndex = msg.indexOf("待支付");
					if (endIndex != -1) {
						rs.setState(Result.HAVE_NO_PAY_TICKET);
						rs.setMsg(msg.substring(beginIndex, endIndex));
					} else if (msg.contains("取消次数过多")) {
						rs.setState(Result.CANCEL_TIMES_TOO_MUCH);
						rs.setMsg(msg);
					} else {
						rs.setState(Result.NO_BOOKED_TICKET);
						rs.setMsg(msg);
					}
				} else {
					rs.setState(Result.NO_BOOKED_TICKET);
					if(msg.contains("您没有未完成的订单")) {
						rs.setMsg("您没有未完成的订单");
					} else {
						rs.setMsg(msg);
					}
				}
			}
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------query order end---------------------");
        return rs;
    }

    String getCode(String url) throws IOException {
        JFrame frame = new JFrame("验证码");
        JLabel label = new JLabel(new ImageIcon(getCodeByte(url)), 0);

        frame.add(label);
        frame.setDefaultCloseOperation(3);
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String rd = br.readLine();
        frame.dispose();
        return rd;
    }

    public byte[] getCodeByte(String url) {
        this.log.debug("-------------------get randcode start-------------------");
        System.out.println("URL :" + url);
        HttpGet get = new HttpGet(url);
        get.addHeader("Accept", "*/*");
        if (url.startsWith(Constants.Login_Code_URL)) {
            get.addHeader("Referer", Constants.Login_Init_URL);
        } else {
            get.addHeader("Referer", Constants.ConfirmPassenger_Init_URL);
        }
        get.addHeader("Accept-Language", "zh-cn");
        get.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)");
        //get.addHeader("Accept-Encoding", "gzip, deflate");
        get.addHeader("Host", Constants.Host_Location);
        //get.addHeader("Connection", "Keep-Alive");
        get.addHeader("Cookie", Constants.getCookie());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            HttpResponse response = this.httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            this.log.debug(response.getStatusLine());
            if (entity != null) {
                InputStream is = entity.getContent();
                byte[] buf = new byte[1024];
                int len = -1;
                while ((len = is.read(buf)) > -1)
                    baos.write(buf, 0, len);
            }
        } catch (Exception e) {
            this.log.error(e);
        }
        this.log.debug("-------------------get randcode end-------------------");
        return baos.toByteArray();
    }
}
